package com.xxdh.controller.user;

import com.alibaba.fastjson.JSON;
import com.xxdh.domain.dto.LoginUserDto;
import com.xxdh.domain.dto.UserDto;
import com.xxdh.domain.po.User;
import com.xxdh.service.IUserExtService;
import com.xxdh.service.IUserService;
import com.xxdh.util.Result;
import com.xxdh.util.UserHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;

@RequestMapping("/user")
@RestController
@RequiredArgsConstructor
@Slf4j
@CrossOrigin(origins = "*")
public class UserController {

    private final IUserService userService;
    private final IUserExtService userExtService;


    @PostMapping("/login")
    public String login(@RequestBody LoginUserDto loginUser, HttpServletResponse response) {
        log.info("loginUser:{}",loginUser.toJSONString());
        boolean flag = userExtService.checkLogin(loginUser,response);
        if(!flag){
            return JSON.toJSONString(Result.fail("用户名或密码错误"));
        }
        userService.finalLogin(loginUser.getUserId(),response);
        return JSON.toJSONString(Result.ok("登录成功"));
    }

    @PostMapping("/register")
    public String register(@RequestBody LoginUserDto loginUser, HttpServletResponse response) {
        log.info("loginUser:{}",loginUser.toJSONString());
        return userService.register(loginUser,response);
    }

    @PostMapping("/update-password")
    public String updatePassword(@RequestBody UserDto userDto) {
        Long userId = UserHolder.getUserId();
        userService.updatePassword(userId,userDto.getNewPassword());
        return Result.ok("修改密码成功").toJSONString();
    }

    @GetMapping("/getUserInfo")
    public String getUserInfo() {
        Long userId = UserHolder.getUserId();
        return Result.ok(userService.getUserById(userId)).toJSONString();
    }

    @PostMapping("/update-userInfo")
    public String updateUserInfo(@RequestBody User user) {
        Long userId = UserHolder.getUserId();
        userService.updateUser(userId,user);
        return Result.ok("修改用户信息成功").toJSONString();
    }

}
